<template>
  <div class="user-folder">
    <div class="header-modal">
      <div class="breadcrumb">
        <p @click="attr = 'folder'">
          文件夹列表
          <i v-if="(userInfo.id === userId && attr === 'folder')">可拖动重新排序</i>
        </p>
        <em v-show="attr === 'site'" class="ri-arrow-drop-left-line"></em>
        <p v-show="attr === 'site'">{{ currentFolder ? currentFolder.name : '' }}</p>
      </div>
      <div
        class="create"
        v-if="userInfo.id === userId"
        @click="showModalVisible">
        <i class="ri-folders-line"></i>
        <p>{{ attr === 'folder' ? '创建文件夹' : '新增站点' }}</p>
      </div>
    </div>
    <div class="folders-modal" v-if="attr === 'folder'">
      <div v-if="loading" style="background: #fff; padding: 12px">
        <a-skeleton active />
      </div>
      <div
        v-if="(!folderList.length && !loading)"
        style="padding: 30px 0; background: #fff"
      >
        <a-empty
          description="用户还未创建文件夹"
          :image="require('~/assets/images/nodata.png')"
        />
      </div>
      <div class="folder-list">
        <draggable  v-model="folderList"
          :animation="200"
          :touchStartThreshold="5"
          :draggable="userInfo.id === userId ? '.folder-list-item' : ''"
          chosen-class="chosen-folder-item"
          drag-class="drag-folder-item"
          :force-fallback="true"
          @sort="handlerDragStart">
          <transition-group>
            <div
              class="folder-list-item"
              @dblclick="archiveFolder(item)"
              v-for="item in folderList"
              :key="item.id">
              <img src="@/assets/images/folder.png" alt="folder">
              <p>{{ item.name }} <em v-if="item.isPrivate === '1'" class="ri-lock-2-line"></em></p>
              <a-popover
                v-if="userInfo.id === userId"
                placement="bottomRight"
              >
                <template slot="content">
                  <div class="artile-list-operate">
                    <p @click="currentFolder = item; folderVisible = true">
                      <a-icon type="edit" />编辑
                    </p>
                    <p @click="deleteFolder(item.id)">
                      <a-icon type="delete" />删除
                    </p>
                  </div>
                </template>
                <div class="operate-fixed" @click.stop>
                  <a-icon type="more" />
                </div>
              </a-popover>
            </div>
          </transition-group>
        </draggable>
      </div>
    </div>
    <div class="sites-modal" v-if="attr === 'site'">
      <p class="sites-modal-tip" v-if="tip">{{ tip }}</p>
      <div class="site-list">
        <div class="site-list-item"
          v-for="item in siteList"
          :key="item.id">
          <div class="img_icon">
            <img :src="item.icon || require('~/assets/images/folder.png')" alt="link">
          </div>
          <div class="l_info">
            <p>{{ item.name }}</p>
            <a target="_blank" :href="item.url">{{ item.siteDesc }}</a>
          </div>
          <a-popover
            v-if="userInfo.id === userId"
            placement="bottomRight"
          >
            <template slot="content">
              <div class="artile-list-operate">
                <p @click="currentSite = item; siteVisible = true">
                  <a-icon type="edit" />编辑
                </p>
                <p @click="deleteSite(item.id)">
                  <a-icon type="delete" />删除
                </p>
              </div>
            </template>
            <div class="operate-fixed" style="cursor: pointer;" @click.stop>
              <a-icon type="more" />
            </div>
          </a-popover>
        </div>
      </div>
    </div>
    <FolderOperateModal
      v-if="folderVisible"
      @close-modal="closeModalVisible"
      :folderInfo="currentFolder"
       />
    <SiteOperateModal
      v-if="siteVisible"
      @close-modal="closeModalVisible"
      :siteInfo="currentSite"
      :folderId="currentFolder.id" />
  </div>
</template>

<script>
import { mapState } from 'vuex'
import draggable from 'vuedraggable'
import FolderOperateModal from '../components/FolderOperateModal'
import SiteOperateModal from '../components/SiteOperateModal'
export default {
  name: 'UserFolder',
  components: { draggable, FolderOperateModal, SiteOperateModal },
  props: {
    userId: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      attr: 'folder',
      tip: '正在打开文件夹',
      loading: true,
      folderVisible: false,
      siteVisible: false,
      folderList: [],
      siteList: [],
      currentFolder: null,
      currentSite: null
    }
  },

  created () {
    this.findSiteFolderList()
  },

  methods: {
    /**
     * 根据用户id查询该用户下的所有文件夹列表
     */
    async findSiteFolderList () {
      try {
        const { data } = await this.$axios.get(`/gimishare/api/v1/site/folder/list?userId=${this.userId}`)
        this.folderList = data
      } catch (error) {
        console.log(error)
      } finally {
        this.loading = false
      }
    },

    /**
     * 查询当前文件夹下的所有站点
     * @param { Object } folderItem
     */
    archiveFolder (folderItem) {
      this.siteList = []
      this.attr = 'site'
      this.tip = '正在打开文件夹'
      this.currentFolder = folderItem
      this.findSitesByFolderId()
    },

    /**
     * 根据文件夹id查询文件夹下所有站点list
     */
    async findSitesByFolderId () {
      try {
        const { data } = await this.$axios.get(`/gimishare/api/v1/sites?folderId=${this.currentFolder.id}`)
        this.siteList = data
        if (!this.siteList.length) {
          this.tip = '当前文件夹为空'
        } else {
          this.tip = ''
        }
      } catch (error) {
        this.tip = '当前文件夹为空'
      }
    },

    /**
     * 删除文件夹同时删除文件夹下的所有站点信息
     * @param { String } folderId  文件夹id
     */
    deleteFolder (folderId) {
      this.$confirm({
        title: '删除文件夹',
        content: '删除文件夹会将该文件夹内的站点全部删除并且不可恢复，确认删除？',
        cancelText: '取消',
        onOk: async () => {
          try {
            await this.$axios.post('/gimishare/api/v1/site/folder/delete', { id: folderId })
            const idx = this.folderList.findIndex(o => o.id === folderId)
            if (idx > -1) {
              this.folderList.splice(idx, 1)
            }
            this.$message.success('删除文件夹成功')
          } catch (error) {
            console.log(error)
          }
        }
      })
    },

    /**
     * 删除站点信息
     */
    deleteSite (siteId) {
      this.$confirm({
        title: '删除站点',
        content: '删除站点后不可恢复，确认删除？',
        cancelText: '取消',
        onOk: async () => {
          try {
            await this.$axios.get(`/gimishare/api/v1/sites/delete?id=${siteId}`)
            const idx = this.siteList.findIndex(o => o.id === siteId)
            if (idx > -1) {
              this.siteList.splice(idx, 1)
              !this.siteList.length && (this.tip = '当前文件夹为空')
            }
            this.$message.success('删除站点成功')
          } catch (error) {
            console.log(error)
          }
        }
      })
    },

    async handlerDragStart () {
      try {
        const ids = this.folderList.map(o => o.id)
        await this.$axios.post('/gimishare/api/v1/site/folder/sort', { ids })
      } catch (error) {
        console.log(error)
      }
    },

    showModalVisible () {
      if (this.attr === 'folder') {
        this.currentFolder = null
        this.folderVisible = true
      } else if (this.attr === 'site') {
        this.siteVisible = true
        this.currentSite = null
      }
    },

    closeModalVisible (render) {
      if (render) {
        switch (this.attr) {
          case 'folder':
            this.findSiteFolderList()
            break
          case 'site':
            this.findSitesByFolderId()
            break
        }
      }
      this.folderVisible = false
      this.siteVisible = false
    }
  },

  computed: {
    ...mapState({
      userInfo: (state) => state.userInfo
    })
  }
}
</script>

<style scoped lang="less">
.user-folder {
  background: #fff;
  padding-bottom: 12px;
  .header-modal {
    display: flex;
    justify-content: space-between;
    padding: 10px 12px;
    border-bottom: 1px solid #f1f1f1;
    .breadcrumb {
      display: flex;
      align-items: center;
      em {
        color: #999;
        font-size: 20px;
      }
      p {
        color: #000;
        font-size: 12px;
        &:first-child {
          cursor: pointer;
        }
        &:nth-of-type(2) {
          color: #999;
        }
        i {
          font-style: normal;
          font-size: 11px;
          color: #999;
          margin-left: 6px;
        }
      }
    }
    .create {
      cursor: pointer;
      color: #000;
      user-select: none;
      display: flex;
      align-items: center;
      i {
        font-size: 18px;
        position: relative;
        top: 1px;
      }
      p {
        font-size: 12px;
        letter-spacing: 1px;
        margin-left: 6px;
      }
    }
  }
  .folders-modal {
    .folder-list {
      padding-top: 12px;
      &-item {
        display: flex;
        align-items: center;
        padding: 0 12px;
        height: 42px;
        cursor: pointer;
        user-select: none;
        &:hover {
          background: #eeeef380;
        }
        img {
          width: 20px;
          flex-shrink: 0;
          display: block;
        }
        p {
          margin-left: 8px;
          color: #000;
          font-size: 12px;
          flex: 1;
          width: 0;
          em {
            color: #4c4c4c;
            margin-left: 6px;
            font-size: 14px;
          }
        }
      }
      .drag-folder-item {
        border: 2px solid var(--primary-color);
      }
    }
  }
  .sites-modal {
    padding-top: 12px;
    &-tip {
      text-align: center;
      font-size: 12px;
      color: #4c4c4c;
      padding-top: 12px;
    }
    .site-list {
      padding: 0 12px;
      &-item {
        margin: 12px auto;
        display: flex;
        align-items: center;
        .img_icon {
          margin-right: 8px;
          img {
            width: 22px;
            display: block;
            height: 22px;
            object-fit: cover;
          }
        }
        .l_info {
          flex: 1;
          width: 0;
          padding-right: 12px;
          p {
            color: #333;
            font-size: 13px;
          }
          a {
            color: #999;
            font-size: 12px;
            display: block;
            white-space: nowrap;
            text-overflow: ellipsis;
            overflow: hidden;
          }
        }
      }
    }
  }
}
</style>
